import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store/index'
import { Toast } from "vant";
//同步引入组件，需要加载完组件后,再加载下面的部分
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'

//声明路由list
//ts泛型：类型不定，推断
const routes: Array<RouteRecordRaw> = [
  {
    path: '',
    redirect: '/splash'
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      title: '主页面',
      islogin: true
    },
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录页面',
      islogin: true
    },
    component: () => import('../views/login.vue')
  },
  {
    path: '/tslogin',
    name: 'tslogin',
    meta: {
      title: '登录测试页面',
      islogin: true
    },
    component: () => import('../views/ts-login.vue')
  },
  {
    path: '/tsmain',
    name: 'tsmain',
    meta: {
      title: '登录主页面',
      islogin: true
    },
    // 重定向到分类列表，默认进来第一个进行展示
    redirect:'/tsbanner',
    children:[
      {
        path: '/tsbanner',
        name: 'tsbanner',
        meta: {
          title: 'banner列表',
          islogin: true,
          isShow: true
        },
        component: () => import('../views/ts-banner.vue')
      },
      {
        path: '/tsclass',
        name: 'tsclass',
        meta: {
          title: '分类列表',
          islogin: true,
          isShow: true
        },
        component: () => import('../views/ts-class.vue')
      },
      {
        path: '/tsuser',
        name: 'tsuser',
        meta: {
          title: '用户列表',
          islogin: true,
          isShow: true
        },
        component: () => import('../views/ts-user.vue')
      }
    ],
    component: () => import('../views/ts-main.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: AboutView
  },
  {
    path: '/splash',
    name: 'splash',
    component: () => import('../views/splash.vue')
  },
  {
    path: '/toRow',
    name: 'toRow',
    // 异步引入组件优化性
    component: () => import('../views/toRowAndMarkRow.vue')
  },
  {
    path: '/customRef',
    name: 'customRef',
    component: () => import('../views/ManualRef.vue')
  }
]


/*createWebHashHistory的链接后面要加#*/
/*createWebHistory的链接后面不需要加#*/
const router = createRouter({
  history: createWebHashHistory(process.env.BASE_URL),
  routes
})


//路由守卫
//只要进到了某个路由就会执行该方法
router.beforeEach((to, from, next) => {
  //from从哪个路由跳转的

  //to到达的路由

  // 只有执行了next页面才会渲染

  //判断用户是否登录

  /*修改头部标题信息*/


  if (to.meta.islogin) {
    if (store.state.userInfo.token || to.path == '/login' || to.path == '/tslogin') {
      next();
    } else {
      Toast({
        message: '请登录',
        icon: 'contact',
      });
      next({ path: '/login' });
    }
  } else {
    next();
  }


  next()
})

export default router
